//
//  ZBYAppleLoginTool.swift
//  LoginModule
//
//  Created by xianquan on 2024/4/11.
//

import CommonTools
import AuthenticationServices

/// AppleId 登录
class AppleLoginManager: NSObject{
    static let share = AppleLoginManager()
    
    private override init(){}
    
    /// 失败回调
    private var failureHandle:((_ errorType: ErrorType)->Void)?
    
    /// 成功回调
    private var sucessHandle:(( _ identityToken: String,  _ authorizationCode: String, _ user: String, _ nickName: String)->Void)?
}

extension AppleLoginManager{
    
    /// 登录苹果ID
    /// - Parameters:
    ///   - sucessHandle: 成功回调
    ///   - failureHandle: 失败回调
    func loginAppleId(sucessHandle:(( _ identityToken: String,
                                      _ authorizationCode: String,
                                      _ user: String,
                                      _ nickName: String)->Void)?,
                      failureHandle:(( _ errorType: ErrorType)->Void)?){
        if #available(iOS 13.0, *) {
            self.sucessHandle = sucessHandle
            self.failureHandle = failureHandle
            //基于用户的Apple ID 授权用户，生成用户授权请求的一种机制
            let appleIdProvider =  ASAuthorizationAppleIDProvider()
            //创建新的Apple ID授权请求
            let request = appleIdProvider.createRequest()
            //在用户授权期间请求的联系信息
            request.requestedScopes = [ASAuthorization.Scope.email, ASAuthorization.Scope.fullName]
            //由ASAuthorizationAppleIDProvider创建的授权请求，管理授权请求的控制器
            let controller = ASAuthorizationController.init(authorizationRequests: [request])
            //设置授权控制器通知授权请求的成功与失败的代理
            controller.delegate = self;
            //提供展示上下文的代理，在这个上下文中，系统可以展示授权界面给用户
            controller.presentationContextProvider = self;
            controller.performRequests()
        }
    }
}
//MARK: - 代理 ASAuthorizationControllerDelegate 处理数据回调
extension AppleLoginManager: ASAuthorizationControllerDelegate{

    //授权成功地回调
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential{
            
            // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
            let user = appleIDCredential.user

            // 苹果用户信息 如果授权过，可能无法再次获取该信息
            let fullName = appleIDCredential.fullName
            
            let email = appleIDCredential.email
            
            // 服务器验证需要使用的参数
            
            let identityToken = String(data: appleIDCredential.identityToken ?? Data(), encoding: .utf8) ?? ""
            
            let authorizationCode = String(data: appleIDCredential.authorizationCode ?? Data(), encoding: .utf8) ?? ""
            
            
            // 用于判断当前登录的苹果账号是否是一个真实用户，取值有：unsupported、unknown、likelyReal
            let realUserStatus = appleIDCredential.realUserStatus
            
            //对接登录接口，处理用户登录操作
            sucessHandle?(identityToken, authorizationCode, user, fullName?.nickname ?? "")
        }
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        
        if let error = error as? ASAuthorizationError {
            var type : ErrorType = .unknown
            switch error.code {
            case ASAuthorizationError.canceled:
                type = .canceled
            case ASAuthorizationError.failed:
                type = .failed
            case ASAuthorizationError.invalidResponse:
                type = .invalidResponse
            case ASAuthorizationError.notHandled:
                type = .notHandled
            case ASAuthorizationError.unknown:
                type = .unknown
            default:
                break
            }
            failureHandle?(type)
        }
        
    }
}

//MARK: - 代理 ASAuthorizationControllerPresentationContextProviding 管理视图弹出在哪里
extension AppleLoginManager: ASAuthorizationControllerPresentationContextProviding{
    @available(iOS 13.0, *)
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return keyWindow
    }
}


extension AppleLoginManager {
    enum ErrorType: String {
        case canceled = "用户取消了授权请求"
        case failed = "授权请求失败"
        case invalidResponse = "授权请求无响应"
        case notHandled = "未能处理授权请求"
        case unknown = "授权请求失败原因未知"
    }
}
